package test;

import net.rubyeye.xmemcached.MemcachedClient;
import org.springframework.cache.Cache;
import org.springframework.cache.support.SimpleValueWrapper;

/**
 * Created by dws on 2018/3/29.
 * 配置spring-cache的实现方式为xmemcached
 */
public class XCache implements Cache {

    private XMemcachedCache xcache;
    private String namespace;

    public XCache(String namespace,int expire,int timeout, MemcachedClient client, String serverPath) {
        this.xcache = new XMemcachedCache(namespace,expire,timeout, client, serverPath);
        this.namespace = namespace;
    }

    @Override
    public String getName() {
        return this.namespace;
    }

    @Override
    public Object getNativeCache() {
        return this.xcache;
    }

    @Override
    public ValueWrapper get(Object key) {
        if (key == null) return null;
        Object value = xcache.getValue(key.toString(), null);
        return value == null ? null : new SimpleValueWrapper(value);
    }

    @Override
    public <T> T get(Object key, Class<T> type) {
        if (key == null) return null;
        return xcache.getValue(key.toString(), null);
    }

    @Override
    public void put(Object key, Object value) {
        xcache.setValue(key.toString(), value);
    }

    @Override
    public ValueWrapper putIfAbsent(Object key, Object value) {
        put(key, value);
        return get(key);
    }

    //删除
    @Override
    public void evict(Object key) {
        if (key == null) return;
        xcache.deleValue(String.valueOf(key));
    }

    @Override
    public void clear() {
        xcache.deleNameSpaceValue();
    }
}
